package com.narata.netty.rpc;

import com.narata.netty.message.RpcRequestMessage;
import com.narata.netty.message.RpcResponseMessage;
import com.narata.netty.service.HelloService;
import com.narata.netty.service.ServicesFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 18:41 2022-06-26
 * @Modified By:
 **/
@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) {

        RpcResponseMessage response = new RpcResponseMessage();
        try {

            HelloService service = (HelloService) ServicesFactory.getService(Class.forName(msg.getInterfaceName()));
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterType());
            Object invoke = method.invoke(service, msg.getParameterValue());

            response.setReturnValue(invoke);
        } catch (Exception e) {
            e.printStackTrace();
            response.setExceptionValue(e);
        }

        ctx.writeAndFlush(response);
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//        RpcRequestMessage requestMessage = new RpcRequestMessage(1,"com.narata.netty.service.HelloService","sayHello", String.class,  new Class[]{String.class}, new Object[]{"张三"});
//
//        HelloService service = (HelloService) ServicesFactory.getService(Class.forName(requestMessage.getInterfaceName()));
//        Method method = service.getClass().getMethod(requestMessage.getMethodName(), requestMessage.getParameterType());
//        Object invoke = method.invoke(service, requestMessage.getParameterValue());
//        System.out.println(invoke);

    }
}
